<template>
  <div class="announcements-container">
    <van-nav-bar
      title="公告"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 公告分类标签 -->
    <van-tabs v-model="activeTab" sticky>
      <van-tab title="全部" name="all" />
      <van-tab title="通知" name="notice" />
      <van-tab title="活动" name="activity" />
      <van-tab title="科普" name="science" />
    </van-tabs>

    <!-- 公告列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- 置顶公告 -->
        <template v-if="currentPage === 1">
          <van-cell-group v-for="item in topAnnouncements" :key="item.id" inset class="my-2">
            <van-cell
              :title="item.title"
              :label="formatDateTime(item.publishTime)"
              is-link
              @click="router.push(`/announcement/${item.id}`)"
            >
              <template #icon>
                <van-tag type="danger" class="mr-2">置顶</van-tag>
              </template>
              <template #right-icon>
                <van-tag :type="getTypeTag(item.type)">{{ getTypeText(item.type) }}</van-tag>
              </template>
            </van-cell>
            <van-cell>
              <template #title>
                <div class="text-sm text-gray-500 line-clamp-2">{{ item.summary }}</div>
              </template>
            </van-cell>
          </van-cell-group>
        </template>

        <!-- 普通公告 -->
        <van-cell-group v-for="item in announcements" :key="item.id" inset class="my-2">
          <van-cell
            :title="item.title"
            :label="formatDateTime(item.publishTime)"
            is-link
            @click="router.push(`/announcement/${item.id}`)"
          >
            <template #right-icon>
              <van-tag :type="getTypeTag(item.type)">{{ getTypeText(item.type) }}</van-tag>
            </template>
          </van-cell>
          <van-cell>
            <template #title>
              <div class="text-sm text-gray-500 line-clamp-2">{{ item.summary }}</div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <!-- 无公告提示 -->
    <div v-if="!loading && announcements.length === 0 && topAnnouncements.length === 0" class="empty-tip">
      <van-empty description="暂无公告" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getAnnouncements } from '../api'

const router = useRouter()
const activeTab = ref('all')
const announcements = ref([])
const topAnnouncements = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 加载公告列表
const loadAnnouncements = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize,
      type: activeTab.value === 'all' ? undefined : activeTab.value
    }

    const res = await getAnnouncements(params)
    
    if (refreshing.value) {
      announcements.value = []
      topAnnouncements.value = []
      refreshing.value = false
    }
    
    // 第一页时，分离置顶公告
    if (currentPage.value === 1) {
      topAnnouncements.value = res.content.filter(item => item.isTop)
      announcements.value = res.content.filter(item => !item.isTop)
    } else {
      announcements.value.push(...res.content.filter(item => !item.isTop))
    }
    
    loading.value = false
    
    if (res.content.length < pageSize) {
      finished.value = true
    } else {
      currentPage.value += 1
    }
  } catch (error) {
    console.error('获取公告列表失败：', error)
    showToast('获取公告列表失败')
    loading.value = false
  }
}

const onLoad = () => {
  loadAnnouncements()
}

const onRefresh = () => {
  finished.value = false
  currentPage.value = 1
  loadAnnouncements()
}

// 监听标签切换
watch(activeTab, () => {
  announcements.value = []
  topAnnouncements.value = []
  finished.value = false
  currentPage.value = 1
  loadAnnouncements()
})

// 工具函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const getTypeTag = (type) => {
  const tags = {
    notice: 'primary',
    activity: 'success',
    science: 'warning'
  }
  return tags[type] || 'default'
}

const getTypeText = (type) => {
  const texts = {
    notice: '通知',
    activity: '活动',
    science: '科普'
  }
  return texts[type] || '其他'
}

onMounted(() => {
  loadAnnouncements()
})
</script>

<style scoped>
.announcements-container {
  min-height: 100vh;
  background-color: var(--background-color);
}

.empty-tip {
  padding: 40px 0;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style> 